package com.pan.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import sun.reflect.annotation.AnnotationType;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedType;

@Service
@Slf4j
public class BeanService {

    @Autowired
    ApplicationContext applicationContext;

    public void printAllBeanName(){

        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();

        for (String beanDefinitionName : beanDefinitionNames) {
            //
            log.info(beanDefinitionName);
        }

        AutowireCapableBeanFactory autowireCapableBeanFactory = applicationContext.getAutowireCapableBeanFactory();

    }



    public Object getBeanByName(String beanName) {

        Object bean = applicationContext.getBean(beanName);
        if(null==bean){
            log.info("the bean you find is not exist;");
        }

        return bean;
    }



    public String[] getBeanByAnnotation(String annotation) {

        ClassLoader classLoader = applicationContext.getClassLoader();

        String[] beanNamesForAnnotation = new String[0];
        try {

            Class<?> aClass = classLoader.loadClass(annotation);
            aClass.getAnnotatedSuperclass();
            Annotation[] annotations = aClass.getAnnotations();
            Annotation wow = annotations[0];

            beanNamesForAnnotation = applicationContext.getBeanNamesForAnnotation(wow.getClass());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        if(null==beanNamesForAnnotation){
            log.info("the bean you find is not exist;");
        }

        applicationContext.getBeansWithAnnotation(Service.class);

        return beanNamesForAnnotation;
    }


}
